<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------

class ShortcutAction extends NewzanAction{

    private static $source = array(
                0 => 'summary',
                1 => 'pc',
                2 => 'wireless'
            );
    
    public function index($value='')
    {
        $this->redirect('noshow');
    }

    /**
     * 快捷功能-无展现词处理 - view
     * @return void
     */
    public function noshow()
    {
        $this->loadJS('custom.affix','custom.appbar','daterangepicker','date','jquery.sparkline','noshow/noshow','component\component.campaign.reports');
        $campaignMdl = D("Campaign");
        $campaigns = $campaignMdl->getCampaigns($this->me['user_id'], false);
        $this->assign('campaigns', $campaigns);
        $this->display();
    }

    /**
     * 快捷功能-无展现词处理 - Action
     * @return [type] [description]
     */
    public function keywords_update()
    {
        $resp = array();
        $result = array();
        $campaign_iids = $_POST['campaign_iids'];
        $action = $_POST['action'];
        $from = $_POST['from'];
        $to = $_POST['to'];
        if(!is_array($campaign_iids) || !in_array($action, array('delete','activate'))) {
            $result['code'] = 'error';
            $result['msg'] = '参数不正确';
            $this->display_json($result);
            exit();
        }
        $qTime = strtotime($to);
        $checkTime = 15*24*3600;
        $keywordMdl = new KeywordModel();
        $keywords = $keywordMdl->noShowkeyword($this->me['user_id'], $campaign_iids, $from, $to);
        if($keywords['total_items'] > 0) {
            $res = array();
            $column = $action == 'delete' ? 'campaign_id' : 'adgroup_id';
            foreach ($keywords['items'] as $key => $keyword) {
                if($qTime-strtotime($value['create_time']) < $checkTime) {
                    unset($keywords['items'][$key]);
                    --$keywords['total_items'];
                }

                $res[$keyword[$column]][] = $keyword;
            }

            switch ($action) {
                case 'delete': // 删除无展现词
                    if($res) {
                        foreach ($res as $campaign_id => $cWork) {
                            $keyword_ids = array_column($cWork, 'keyword_id');
                            $keywordMdl->deleteKeywords($keyword_ids, $campaign_id);
                        }
                    }
                    break;
                case 'activate': // 激活无展现词
                    foreach ($res as $adgroup_id => $cWork) {
                        $update_keywords = array();
                        foreach ($cWork as $key => $keyword) {
                            $update_keywords[] = array(
                                    'word' => $keyword['word'],
                                    'max_price' => (int)$keyword['max_price']+1,
                                    'matchscope' => $keyword['matchscope'],
                                    'keyword_id' => $keyword['keyword_id']
                                );
                        }
                        $keywordMdl->updateKeywords($adgroup_id, $update_keywords);
                    }
                    break;
            }
        }
        $result['code'] = 'success';
        $result['msg'] = "操作成功，共优化了{$keywords['total_items']}个关键词";
        $this->display_json($result);
    }

    /**
     * 快捷功能-关键词批量优化 - view - step_1
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function campaigns($value='')
    {
        $siluAdd = (int)cookie('isCustomSiluAdd');
        $siluAdd = $siluAdd === 1 ? true : false;
        $this->assign('siluAdd', $siluAdd);
        cookie('isCustomSiluAdd', 0);

        $kaweiAdd = (int)cookie('iskaweiAdd');
        $kaweiAdd = $kaweiAdd === 1 ? true : false;
        $this->assign('kaweiAdd', $kaweiAdd);
        cookie('iskaweiAdd', 0);

        $showSilu = (int)cookie('showSilu');
        // $showSilu = $showSilu === 1 ? true : false;
        if($showSilu === 1) {
            // 我的思路我牛逼
            $showSilu = true;
            $myThinking = M('semiautotag')->field('id, title')->where("type = 4 and type_value = {$this->me['user_id']}")->select();
            $this->assign('myThinking', $myThinking);
            
            $siluInfo = cookie('showSiluInfo');
            // dump($siluInfo);
            // die;
            $this->assign('siluInfo', (array)$siluInfo);
            cookie('showSiluInfo', 0);
        } else {
            $showSilu = false;
        }
        $this->assign('showSilu', $showSilu);
        cookie('showSilu', 0);
        
        $this->loadJS('custom.affix','custom.appbar','daterangepicker','date','jquery.sparkline','manage','custom.keywordhelper','custom.keywordmanager', 'custom.siluhelper');
        $this->display();
    }

    public function ranking_campaigns($value=''){
        $this->assign('campaign_id',  $_GET['campaign_id']);
        $this->assign('device',  $_GET['device']);
        $this->loadJS('custom.affix','custom.appbar','daterangepicker','date','jquery.sparkline','manage','custom.keywordhelper','custom.keywordmanager',
            'component/component.campaign.reports','ranking/campaigns_selector');
        $this->display();
    }

    public function ranking_adgroups($value=''){
        $this->assign('campaign_id',  $_GET['campaign_id']);
        $this->assign('adgroup_id',  $_GET['adgroup_id']);
        $this->assign('device',  $_GET['device']);
        $this->loadJS('custom.affix','custom.appbar','daterangepicker','date','jquery.sparkline','manage',
             'component/component.adgroup.reports', 'ranking/adgroups_selector');
        $this->display();
    }

    public function ranking_keywords($value=''){
        $this->assign('adgroup_id',  $_GET['adgroup_id']);
        $this->assign('keyword_ids',  $_GET['keyword_ids']);
        $this->assign('campaign_id',  $_GET['campaign_id']);
        $this->assign('device',  $_GET['device']);
        $this->loadJS('custom.affix','custom.appbar','daterangepicker','date','jquery.sparkline','manage',
            'component/component.keyword.manager', 'ranking/keywords_selector');
        $this->display();
    }
    public function ranking_rules($value=''){
        $this->assign('keyword_id',  $_GET['keyword_id']);
        $this->assign('keyword_ids',  $_GET['keyword_ids']);
        $this->assign('tactics_id',  $_GET['tactics_id']);
        $this->assign('adgroup_id',  $_GET['adgroup_id']);
        $this->assign('campaign_id',  $_GET['campaign_id']);
        $this->assign('device',  $_GET['device']);
        $this->loadJS('ranking/ranking_editor');
        $this->display();
    }

    public function keywords()
    {
        $keywordIDs = $this->_post('kids');
        $keywordMdl = new KeywordModel();
        $keywords = $keywordMdl->getKeywords($this->me['user_id'], $keywordIDs);
        $products = array();
        $campaigns = array();

        $ranks = array();
        foreach($keywords as $key => $keyword){
            $rank = array();
            $rank['keyword_id'] = $keyword['keyword_id'];
            $rank['keyword'] = $keyword['word'];
            $rank['campaign_id'] = $keyword['campaign_id'];
            $rank['adgroup_id'] = $keyword['adgroup_id'];
            $rank['max_price'] = $keyword['max_price'];
            $rank['max_mobile_price'] = $keyword['max_mobile_price'];

            if(!$products[$keyword['adgroup_id']]){
                $adgroupMdl = new AdgroupModel();
                $productMdl = new ProductModel();
                $adgroup = $adgroupMdl->getAdgroupByAdgroupId($this->me['user_id'], $keyword['adgroup_id']);
                if($adgroup){
                    $products[$keyword['adgroup_id']] = $productMdl->getProductById($adgroup['num_iid']);
                }
            }
            if($products[$keyword['adgroup_id']]){
                $rank['item_title'] = $products[$keyword['adgroup_id']]['title'];
            }

            if(!$campaigns[$keyword['campaign_id']]){
                $campaignMdl = new CampaignModel();
                $ret = $campaignMdl->getCampaignById($this->me['user_id'], $keyword['campaign_id']);
                $campaigns[$keyword['campaign_id']] = $ret['campaign'];
            }
            if($campaigns[$keyword['campaign_id']]){
                $rank['campaign_title'] = $campaigns[$keyword['campaign_id']]['title'];
            }

            $rank['real_rank'] = 0;

            $ranks[] = $rank;
        }

        $this->display_json(array(
                'result' => true,
                'keywords' => $ranks
            )
        );
    }

    /**
     * 快捷功能-关键词批量优化 - view - step_2
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function keywordsbatch()
    {   
        $kaweiSetting = cookie('kaweiSetting');
        $is_run_kawei = false;

        // 是否启动卡位界面
//        if($kaweiSetting) {
            // cookie('kaweiSetting', null);
            $is_run_kawei = true;
            // $this->assign('path', tempStr($kaweiSetting, stripos($kaweiSetting, 'campaign_id')));
            $url = explode('?', $kaweiSetting);
            $y = array();
            foreach ($url as $key => $value) {
                if(strpos($value, 'campaign_id') !== false || strpos($value, 'adgroup_id') !== false) {
                    $y[] = $value;
                }
            }
            if($y) {
                $y = implode('&', $y);
            } else {
                $y = '';
            }
            $this->assign('path', $y);
            $this->loadJS('custom.affix','custom.appbar','daterangepicker','date','jquery.sparkline','manage','component/component.keyword.manager');
//        } else{
//            redirect('/index');
//            // $this->loadJS('custom.affix','custom.appbar','daterangepicker','date','jquery.sparkline','manage','custom.keywordhelper','custom.keywordbatchmanager');
//        }
        
        $campaign_id = $_GET['campaign_id'];
        $adgroup_id = $_GET['adgroup_id'];
        // $campaign_id_array = explode(',', urldecode($campaign_id));
        
        // 获取所有的推广计划
        $campaignMdl = D("Campaign");
        $campaigns = $campaignMdl->getCampaigns($this->me['user_id'], false);
        $this->assign('campaigns', $campaigns);
        // $campaign_info =  $campaignMdl->getCampaignInfo($this->me['user_id'], $campaign_id);
        // $this->assign('campaign_info', $campaign_info['title']);
        
        $this->assign('campaign_id', $campaign_id);
        $this->assign('adgroup_id', $adgroup_id);
        
        $is_run_myThink = array();
        $is_run_myThink['status'] = ($_GET['type'] == 'myThinking') ? 'true' : 'false';
        if($is_run_myThink['status'] == 'true') {
            $is_run_myThink['value'] = $_GET['myThinking'];
        } else {
           $is_run_myThink['value'] = 0; 
        }
        $this->assign('is_run_myThink', $is_run_myThink);
        $this->assign('is_run_kawei', $is_run_kawei);

        // 获取操作的时间
        $skName = "keyword_batch_time{$this->me['user_id']}-{$campaign_id}";
        $this->time_search = session('?'.$skName) ? session($skName) : array('from'=> date('Y-m-d', strtotime('-1 day')),'to'=>date('Y-m-d', strtotime('-1 day')));

        $this->display();
    }

    /**
     * 快捷功能-关键词批量优化 - Action - 获取关键词报表
     * @return [type] [description]
     */
    public function keywordsbatchmanager()
    {

        $params = $_POST;
        $sourceType = (isset($params['platform']) && in_array($params['platform'], array(0,1,2)))? self::$source[$params['platform']] : self::$source[0] ; // 0 summary , 1 pc , 2 wireless
        // 分页
        $page_size = (int)$params['pageSize']; // 每页显示数量
        $current_page = $params['currentPage']; // 当前页数
        if(!$current_page || (int)$current_page < 0) {
            $current_page = 1;
        }

        $user_id = $this->me['user_id'];
        $campaign_id = $_POST['campaign_id']; // 获取要查询的计划 
        $campaign_id = (strtolower($campaign_id) == 'all') ? -1 : explode(',', urldecode($campaign_id));
        // $campaign_id_array = explode(',', urldecode($campaign_id));

        // 获取单独选择的推广组
        $post_adgroup_id = $_POST['adgroup_id'];
        $post_adgroup_id = $post_adgroup_id ? explode(',', urldecode($post_adgroup_id)) : -1;

        $from = $_POST['from'];
        $to = $_POST['to'];

        // 记录选择的时间
        $skName = "{$params['action_type']}_time{$user_id}-{$campaign_id}";
        session($skName, array(
                'from'=> $params['from'],
                'to' => $params['to']
            )
        );

        // 排序
        $sort = $params['sort'];
        $sortType = $params['desc'] == 'true' ? 'desc' : 'asc';
        $sortType_q = $params['desc'] == 'true' ? 'dec' : 'asc';

        // 筛选条件
        $filters = $params['filter'];

        foreach($filters as $k => $f) {
            if(empty($f) || ($f['max'] == 0 && $f['min'] == 0)){
                unset($filters[$k]);
                continue;
            }
            switch($k){
                case 'price':
                    // $filters['max_price'] = $f;
                    // unset( $filters['price'] );
                    if(is_array($f)) {
                    $filters['max_price']['max'] = $f['max'];
                    $filters['max_price']['min'] = $f['min'];
                    } else {
                    $filters['max_price'] = $f;
                    }
                    unset($filters['price']);
                    break;
                case 'cpc':
                case 'cpm':
                case 'ctr':
                case 'cvr':
                    // $filters[$k]['min'] /= 100;
                    // $filters[$k]['max'] /= 100;
                default:
                $filters[$k]['eq'] = true;              
                break;
            }
        } 
        $word = $params['word'];
        if($word){
            $filters['word'] = $word;
        }


        $rpt_keywords = array();
        
        $adgroupMdl = new AdgroupModel;

        // 根据条件（推广计划）获取的推广组
        if(!is_array($campaign_id) && $campaign_id == -1) {
            $adgroups = $adgroupMdl->getUserAdgroupsAll($user_id, false, array('online_status' => 'online')); // 获取全部推广组
        } else {
            $adgroups = array();
            foreach ($campaign_id as $key => $id) {
                $tmp = $adgroupMdl->getCampaignsAdgroups($user_id, $id, false, $from, $to, false, 0, 0, array(), array('online_status' => 'online'));
                if($tmp)
                    $adgroups = array_merge($adgroups, $tmp);
            }
        }

        // 组合所获取的 推广组编号(adgroup_id) 
        // 推广计划内的推广组 跟 单独选择的推广组
        // 并获取关键词报表数据
        if($adgroups || $post_adgroup_id) {
            $adgroup_iids = array();
            if($adgroups)
                $adgroup_iids = array_column($adgroups, 'adgroup_id');
            if($post_adgroup_id && is_array($post_adgroup_id)) {
                $adgroup_iids = array_merge($adgroup_iids, $post_adgroup_id);
            }
            $keywordMdl = new KeywordModel;
            foreach ($adgroup_iids as $key => $adgroup_id) {
                $keywords = $keywordMdl->getKeywordsWithStats('adgroup_id', $adgroup_id, $from, $to, $sort, $sortType, 1, 200, $filters, true, false, $sourceType);
                if($keywords) {
                    $mobile_discount = $adgroupMdl->field('mobile_discount/100 AS mobile_discount')->where(array('user_id' => $user_id, 'adgroup_id'=>$adgroup_id))->getField('mobile_discount');
                    $mobile_discount = floatval($mobile_discount/100);
                    foreach ($keywords as $key => &$keyword) {
                        if((int)$keyword['mobile_is_default_price'] === 1) {
                            $keyword['max_mobile_price'] = floatval(($keyword['max_price'] * $mobile_discount)/100);
                        } else {
                            $keyword['max_mobile_price'] = price_display_str($keyword['max_mobile_price']/100);
                        }
                    }
                }
                $rpt_keywords = array_merge($rpt_keywords, $keywords);
            }
        }
        
        // sort data
        $func = "uc_cmp_{$sort}_{$sortType_q}";
        if($sort)  {
            usort($rpt_keywords, $func);
        }

        // page data
        $keyword_info_count = count($rpt_keywords);
        $total_page = ceil($keyword_info_count/$page_size);
        if($current_page > $total_page) {
            $current_page = 1;
        }
        $page_html = page_html($current_page, $keyword_info_count, $page_size);
        $this->assign('page_html', $page_html);
        $rpt_keywords = array_slice($rpt_keywords, $page_size * ($current_page - 1) , $page_size);
        $this->assign('keywords', $rpt_keywords);

        $this->action_keywords = S("action_keywords_{$user_id}");

        if($params['headerless']){
            $this->display('ranking_keywords_list');
        }else{
            $this->display();
        }
    }

    /**
     * 快捷功能-关键词批量优化 - Action - 
     * @return [type] [description]
     */
    public function shortcut_update()
    {
        $keywords = $_POST['keywords'];
        $result = R('Keyword/keywordsUpdate', array($keywords), 'Event');
        $this->display_json(array( "keywords" => $result) );
    }

    /**
     * 快捷功能-关键词批量优化 - Action - 获取最大值
     * @return [type] [description]
     */
    public function boundary()
    {
        $boundary = array();
        $campaign_id = $_POST['campaign_id'];
        $from = $_POST['from'];
        $to = $_POST['to'];

        // 获取单独选择的推广组
        $post_adgroup_id = $_POST['adgroup_id'];
        $post_adgroup_id = $post_adgroup_id ? explode(',', urldecode($post_adgroup_id)) : -1;

        $keywordMdl = new KeywordModel;
        if(!$campaign_id || (int)$campaign_id == -1) {
            // 整个账户
            $boundary = $keywordMdl->getStatsBoundary('taobao_user_id', $this->me['user_id'] , $from, $to);
        } else {
            // 某个计划
            // $boundary = $keywordMdl->getStatsBoundary('campaign_id', $campaign_id , $from, $to);
            $adgroup_iids = array();
            $adgroups = array();
            $adgroupMdl = new AdgroupModel;
            $campaign_id = explode(',', $campaign_id);
            foreach ($campaign_id as $key => $id) {
                $tmp = $adgroupMdl->getCampaignsAdgroups($this->me['user_id'], $id, false, $from, $to);
                if($tmp)
                    $adgroups = array_merge($adgroups, $tmp);
            }
            
            if($adgroups)
                $adgroup_iids = array_column($adgroups, 'adgroup_id');
            if($post_adgroup_id && is_array($post_adgroup_id))
                $adgroup_iids = array_merge($adgroup_iids, $post_adgroup_id);

            if($adgroup_iids) {
                $boundary = $keywordMdl->getStatsBoundary('adgroup_id', $adgroup_iids , $from, $to);
            }
        }
        
        foreach( $boundary as $ic => $value){
            switch($ic){
                case 'cpc':
                case 'cpm':
                case 'ctr':
                case 'cvr':
                    $max = ceil( $value * 100 );
                break;
                
                default:
                    $max = ceil( $value );
                break;
            }
            $boundary[$ic] = array(
                        'min' => 0,
                        'max' => $max
                    );
        }
        $this->display_json( array('params' => array( 'filter' => $boundary ) ) );
    }
}